/**
 * 客服工作台 API 接口
 * "方舟"客服工作台 (Ark Support Workbench)
 */

import { http } from "@/utils/http";

// ==================== 类型定义 ====================

/** 用户类型 */
export type UserType = "NormalUser" | "AdminUser";

/** 会话状态 */
export type RoomStatus = "new" | "active" | "closed";

/** 消息类型 */
export type MessageType = "text" | "image" | "file" | "system";

/** 聊天室列表数据 */
export interface RoomListResponse {
  code: number;
  message: string;
  data?: {
    rooms: ChatRoom[];
    pagination: {
      page: number;
      per_page: number;
      total: number;
      pages: number;
      has_next: boolean;
      has_prev: boolean;
    };
  };
}
/** 参与者信息 */
export interface Participant {
  id: number;
  type: UserType;
  name: string;
  avatar?: string;
  phone?: string;
  email?: string;
  joined_at?: string;
  registered_at?: string;
  is_online?: boolean;
  online_status?: string;
  last_active_at?: string;
}

/** 消息信息 */
export interface Message {
  id: number;
  room_id: number;
  content: string;
  message_type: MessageType;
  created_at: string;
  sender: {
    id: number;
    type: UserType;
    name: string;
    avatar?: string;
  };
  is_own?: boolean;
}

/** 聊天室信息 */
export interface ChatRoom {
  id: number;
  type: "private" | "group";
  name?: string;
  status?: RoomStatus;
  created_at: string;
  updated_at: string;
  participants: Participant[];
  participant_count: number;
  last_message?: Message;
  unread_count?: number;
  assigned_to?: number; // 分配给哪个管理员
  waiting_time?: number; // 等待时长(秒)
}

/** 用户详细信息 */
export interface UserDetail extends Participant {
  total_sessions?: number; // 总会话数
  resolved_sessions?: number; // 已解决会话数
  average_rating?: number; // 平均评分
  last_contact?: string; // 最后联系时间
  tags?: string[]; // 用户标签
  notes?: string; // 备注
}

/** 快捷回复模板 */
export interface QuickReply {
  id: number;
  title: string;
  content: string;
  category?: string;
  usage_count?: number;
  created_at: string;
}

/** 统计数据 */
export interface Statistics {
  today_received: number; // 今日接待人数
  average_response_time: number; // 平均响应时间(秒)
  resolution_rate: number; // 解决率(百分比)
  online_agents: number; // 在线客服数
  waiting_count: number; // 待处理数量
}

// ==================== API 接口 ====================
const baseUrl = "/chatapi";
/**
 * 获取聊天室列表
 * @param params 查询参数
 */
export const getChatRooms = (params?: {
  page?: number;
  per_page?: number;
  status?: RoomStatus;
  assigned_to?: number;
  include_hidden?: boolean; // 是否包含隐藏的会话
}) => {
  return http.request<RoomListResponse>("get", `${baseUrl}/chat/rooms`, {
    params
  });
};
/**
 * 获取所有聊天室列表
 * @param params 分页参数
 * @returns
 */
export const getAllChatRooms = (params: {
  page?: number;
  per_page?: number;
  room_id?: number | string;
  nickname?: string;
}) => {
  return http.request<RoomListResponse>("get", `${baseUrl}/chat/all-rooms`, {
    params
  });
};

/**
 * 删除聊天室
 * @param room_id 房间ID
 * @param force_delete 是否强制删除
 * @returns
 */
export const deleteChatRoom = (room_id: number, force_delete = false) => {
  return http.request("delete", `${baseUrl}/chat/rooms/${room_id}`, {
    data: { force_delete }
  });
};
/**
 * 获取单个聊天室详情
 * @param roomId 聊天室ID
 */
export const getChatRoomDetail = (roomId: number) => {
  return http.request<{ room: ChatRoom }>("get", `${baseUrl}/chat/rooms/${roomId}`);
};

/**
 * 获取聊天室消息历史
 * @param roomId 聊天室ID
 * @param params 查询参数
 */
export const getRoomMessages = (roomId: number, params?: { page?: number; per_page?: number }) => {
  return http.request<{
    messages: Message[];
    pagination: {
      page: number;
      per_page: number;
      total: number;
      pages: number;
      has_next: boolean;
      has_prev: boolean;
    };
  }>("get", `${baseUrl}/chat/rooms/${roomId}/messages`, { params });
};

/**
 * 发送消息
 * @param roomId 聊天室ID
 * @param data 消息数据
 */
export const sendMessage = (roomId: number, data: { content: string; type: MessageType }) => {
  return http.request<{ message: Message }>("post", `${baseUrl}/chat/rooms/${roomId}/messages`, { data });
};

/**
 * 获取聊天室参与者列表
 * @param roomId 聊天室ID
 */
export const getRoomParticipants = (roomId: number) => {
  return http.request<{
    participants: Participant[];
    count: number;
  }>("get", `${baseUrl}/chat/rooms/${roomId}/participants`);
};

/**
 * 创建聊天室
 * @param data 聊天室数据
 */
export const createChatRoom = (data: {
  type: "private" | "group";
  name?: string;
  participants: Array<{ id: number; type: UserType }>;
}) => {
  return http.request<{ room: ChatRoom }>("post", `${baseUrl}/chat/rooms`, {
    data
  });
};

/**
 * 添加参与者到聊天室
 * @param roomId 聊天室ID
 * @param participants 参与者列表
 */
export const addParticipants = (roomId: number, participants: Array<{ id: number; type: UserType }>) => {
  return http.request<{ added_count: number }>("post", `${baseUrl}/chat/rooms/${roomId}/participants`, {
    data: { participants }
  });
};

// ==================== 客服工作台专用接口 ====================

/**
 * 获取用户详细信息
 * @param userId 用户ID
 * @param userType 用户类型
 */
export const getUserDetail = (userId: number, userType: UserType) => {
  return http.request<{ user: UserDetail }>("get", `${baseUrl}/users/${userType}/${userId}`);
};

/**
 * 获取用户的历史会话列表
 * @param userId 用户ID
 * @param userType 用户类型
 */
export const getUserSessions = (userId: number, userType: UserType) => {
  return http.request<{
    sessions: ChatRoom[];
    total: number;
  }>("get", `${baseUrl}/users/${userType}/${userId}/sessions`);
};

/**
 * 获取客服工作台统计数据
 */
export const getStatistics = () => {
  return http.request<Statistics>("get", `${baseUrl}/customer-service/statistics`);
};

/**
 * 获取快捷回复列表
 * @param category 分类
 */
export const getQuickReplies = (category?: string) => {
  return http.request<{
    replies: QuickReply[];
    total: number;
  }>("get", `${baseUrl}/customer-service/quick-replies`, {
    params: { category }
  });
};

/**
 * 创建快捷回复
 * @param data 快捷回复数据
 */
export const createQuickReply = (data: { title: string; content: string; category?: string }) => {
  return http.request<{ reply: QuickReply }>("post", `${baseUrl}/customer-service/quick-replies`, { data });
};

/**
 * 更新快捷回复
 * @param replyId 回复ID
 * @param data 更新数据
 */
export const updateQuickReply = (replyId: number, data: Partial<QuickReply>) => {
  return http.request<{ reply: QuickReply }>("put", `${baseUrl}/customer-service/quick-replies/${replyId}`, {
    data
  });
};

/**
 * 删除快捷回复
 * @param replyId 回复ID
 */
export const deleteQuickReply = (replyId: number) => {
  return http.request("delete", `${baseUrl}/customer-service/quick-replies/${replyId}`);
};

/**
 * 上传文件
 * @param file 文件对象
 */
export const uploadFile = (file: File) => {
  const formData = new FormData();
  formData.append("file", file);

  return http.request<{
    url: string;
    filename: string;
    size: number;
  }>("post", "/api/upload", {
    data: formData,
    headers: { "Content-Type": "multipart/form-data" }
  });
};

/**
 * 搜索聊天室
 * @param keyword 关键词
 */
export const searchRooms = (keyword: string) => {
  return http.request<{
    rooms: ChatRoom[];
    total: number;
  }>("get", `${baseUrl}/chat/rooms/search`, {
    params: { keyword }
  });
};

/**
 * 隐藏会话（仅对当前参与者不可见）
 * @param roomId 聊天室ID
 */
export const hideRoom = (roomId: number) => {
  return http.request<{
    code: number;
    message: string;
    data: {
      room_id: number;
      room_deleted?: boolean; // 如果双方都删除，房间会被清空
    };
  }>("post", `${baseUrl}/chat/rooms/${roomId}/hide`);
};

/**
 * 恢复会话（取消隐藏）
 * @param roomId 聊天室ID
 */
export const restoreRoom = (roomId: number) => {
  return http.request<{
    code: number;
    message: string;
    data: {
      room_id: number;
    };
  }>("post", `${baseUrl}/chat/rooms/${roomId}/restore`);
};

// ==================== 用户管理 ====================

/** 客户端用户信息 */
export interface ClientUser {
  id: number;
  avatar?: string;
  phone?: string;
  email?: string;
  online_status: boolean;
  last_active_at?: string;
  registered_at: string;
  total_messages?: number;
  last_message_at?: string;
  birthday?: Date | null;
  city?: string | null;
  country?: string | null;
  create_at?: Date;
  description?: string | null;
  enable?: boolean;
  gender?: number;
  is_online: boolean | null;
  nickname: string;
  openid?: string;
  province?: string | null;
  unionid?: string;
  update_at?: Date;
  username?: string;
}

/** 获取客户端用户列表参数 */
export interface GetClientUsersParams {
  page?: number;
  per_page?: number;
  keyword?: string;
  online_only?: boolean;
  sort_by?: "name" | "last_active" | "registered_at";
  order?: "asc" | "desc";
}

/**
 * 获取客户端用户列表
 * @param params 查询参数
 */
export const getClientUsers = (params?: GetClientUsersParams) => {
  return http.request<{
    data?: {
      list: ClientUser[];
      total?: number;
    };
  }>("get", `/api/user/list`, {
    params
  });
};

/**
 * 获取单个客户端用户详情
 * @param userId 用户ID
 */
export const getClientUser = (userId: number) => {
  return http.request<{ user: ClientUser }>("get", `${baseUrl}/customer-service/client-users/${userId}`);
};

/**
 * 创建与用户的聊天室
 * @param userId 用户ID
 */
export const createChatWithUser = (userId: number) => {
  return http.request<{ room: ChatRoom }>("post", `${baseUrl}/chat/rooms`, {
    data: {
      type: "private",
      participants: [{ user_id: userId, user_type: "NormalUser" }]
    }
  });
};

/**
 * 标记聊天室为已读
 * @param roomId 聊天室ID
 */
export const markRoomAsRead = (roomId: number) => {
  return http.request<{ code: number; message: string }>("post", `${baseUrl}/chat/rooms/${roomId}/read`);
};
